import os
from pptx import Presentation

movie_dir = 'top250'

def get_movie_info():
    '''将电影信息读入并整理成一个列表'''
    movies_info = []

    with open(os.path.join(movie_dir, 'douban_movie_top250.txt'), encoding='utf-8')  as f:
        # 一行行读入文件中的内容
        for line in f.readlines():
            # 以'符号作为分割符，将一行文字分割成多份
            l = line.split("'")
            mf = {} # movie info电影信息
            mf['index'] = l[1] # 电影编号
            mf['title'] = l[3] # 电影标题
            mf['score'] = l[5] # 电影分数
            try:
                # 电影描述
                mf['desc'] = l[7]
            except:
                # 有些电影没有描述
                mf['desc'] = ''
            # 电影图片路径
            mf['img_path'] = os.path.join(movie_dir, 'Top250_movie_images', f"{mf['index']}_{mf['title']}.jpg")
            movies_info.append(mf)
    return movies_info


def create_ppt(movies_info):
    # 读入母版ppt文件构建ppt对象
    ppt = Presentation('ppt母版文件.pptx')
    # 获取母版个数
    num = len(ppt.slide_layouts)
    print(num)
    layout = ppt.slide_layouts
    # 遍历所有电影信息
    for mf in movies_info:
        # 安装母版中第一个幻灯片的布局创建新幻灯片
        slide = ppt.slides.add_slide(layout[0])
        # 当前幻灯片汇中所有的占位符
        placeholders = slide.shapes.placeholders
        for i, pl in enumerate(placeholders):
            if i == 0:
                # 电影编号 + 电影标题 插入到第一个占位符对象中
                pl.text = mf['index'] + mf['title']
            elif i == 1:
                # 占位符对象中插入图片，插入到幻灯片中第二个占位符
                pl.insert_picture(mf['img_path'])
            elif i == 2:
                # 电影分数插入到第三个占位符对象中
                pl.text = mf['score']
            elif i == 3:
                # 电影描述插入到第四个占位符对象中
                pl.text = mf['desc']
    ppt.save('豆瓣Top250电影.pptx')

if __name__ == "__main__":
    movies_info = get_movie_info()
    create_ppt(movies_info)